package com.ujiuye.controller;

import com.ujiuye.pojo.Menu;
import com.ujiuye.service.IMenuService;
import com.ujiuye.utils.MessageConstant;
import com.ujiuye.utils.Result;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜单 前端控制器
 * </p>
 *
 * @author zhangwenping
 * @since 2021-07-05
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private IMenuService menuService;

    @GetMapping("/list")
    public Result listAll(){
        try {
            List<Menu> list = menuService.list();
            return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MENU_FAIL);
        }
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") int id){
        try {
            menuService.removeById(id);
            return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_MENU_FAIL);
        }
    }

    @PostMapping
    public Result save(@RequestBody Menu menu){
        try {
            menuService.save(menu);
            return new Result(true,MessageConstant.ADD_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_MENU_FAIL);
        }
    }

    @GetMapping("/{id}")//通过id查询
    public Result getById(@PathVariable("id") int id){
        try {
            Menu menu = menuService.getById(id);
            return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MENU_FAIL);
        }
    }

    @PutMapping//执行修改
    public Result update(@RequestBody Menu menu){
        try {
            menuService.updateById(menu);
            return new Result(true,MessageConstant.EDIT_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MENU_FAIL);
        }
    }

    @PostMapping("/name")//通过菜单名查询
    public Result getByName(String name){
        try {
            Menu menu = menuService.getByName(name);
            return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MENU_FAIL);
        }
    }

}

